/**/
var Browser_Name = navigator.appName;
var Browser_Version = parseFloat(navigator.appVersion);
var Browser_Agent = navigator.userAgent;
var Actual_Version, Actual_Name;
var is_IE = (Browser_Name == "Microsoft Internet Explorer");
if(is_IE) {
	var Version_Start = Browser_Agent.indexOf("MSIE");
	var Version_End = Browser_Agent.indexOf(";", Version_Start);
	Actual_Version = Browser_Agent.substring(Version_Start + 5, Version_End)
	Actual_Name = Browser_Name;
	if(Browser_Agent.indexOf("Maxthon") != -1) {
		Actual_Name += "(Maxthon)";
	}
}
function addBookmark(title,url) 
{
	if($.browser.webkit){ 
		alert("请用CTRL+D收藏本网页！");
		return true;
	}
    if (window.sidebar){ 
        window.sidebar.addPanel(title, url,""); 
    } 
    else if( document.all ){
        window.external.AddFavorite( url, title);
    } 
    else if( window.opera && window.print ){
        return true;
    }
}
function SetHome(obj,url){ 
	if($.browser.webkit){ 
		alert("请手动设置，webkit浏览器暂不支持！");
		return true;
	}
	try{ 
		obj.style.behavior='url(#default#homepage)';
		obj.setHomePage(url); 
	} 
	catch(e){ 
		if(window.netscape) { 
			try { 
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
			} 
			catch (e) { 
				alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将 [signed.applets.codebase_principal_support]的值设置为'true',双击即可。"); 
			} 
			var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); 
			prefs.setCharPref('browser.startup.homepage',url); 
		 } 
	} 
} 
$(function(){ 
	$('input[type="text"],textarea').focus(function(){ 
		$(this).addClass('input_on');
	}).blur(function(){
		$(this).removeClass('input_on');
	});
});
//禁止选择一级分类
function check_cate(obj){ 
	if(parseInt($("option:selected",$(obj)).attr('pid'))==0){
		alert("一级分类禁止选择!");
		$('option[value="0"]',$(obj)).attr('selected','selected');
	}
}
//搜索
function check_search(obj){ 
	var context=$(obj);
	var keywords=$.trim($("input[name='keywords']",context).val());
	if(keywords.length==0||keywords==default_kw)return false;
	//console.log();
	window.location.href=def.root+"index.php?m=search&a=index&keywords="+encodeURIComponent(keywords);
	//console.log(context.attr("action")+"?keywords="+encodeURIComponent(keywords));
	return false;
}
//商品列表
function item_callback(){ 
	$('.encode_url').each(function(){ 
		var url=$(this).attr('url')||"";
		var tag=$(this).attr('tagName').toLowerCase();
		if(tag=='img'){ 
			$(this).attr('src',base64_decode(url));
		}else if(tag=='a'){ 
			$(this).attr('href',base64_decode(url));
		}	
	});	
	//商品喜欢
	$(".like_it,.img_like_btn,.like_btn").click(function(){
		var iid = $(this).attr('iid');
		var iurl = $(this).attr('iurl');
		if(!iurl){ 
			var iurl=window.location.href.substr(0,window.location.href.indexOf('#'));	
		}
		//console.log(iurl);return;
		var btn=$(this);
		$.get(def.root+"index.php?m=item&a=like", { id: iid }, function(data){
			if(data.data=='not_login'){ 
				login();
				return;	
			}else if(data.data=='yet_exist'){ 
				tips(btn.parent(),">_<喜欢过了 <a href='"+iurl+"#items_comments'>再说两句</a>",'yes');
			}else if(data.data>0){ 
				$("#like_num_"+iid).html(parseInt($("#like_num_"+iid).html())+1);				
				tips(btn.parent(),"添加成功! <a href='"+iurl+"#items_comments'>再说两句</a>",'yes');
			}
		},'json'); 
	});
	$('.item').mouseover(function(){ 
		$('.btns',this).show();
	}).mouseout(function(){
		$('.btns',this).hide();		 	
	});			
}
$(function(){
	item_callback();  
	function masonry(){ 
		$('.item img').load(function(){ 
			$('.infinite_scroll').masonry({ 
				itemSelector: '.masonry_brick',
				columnWidth:226,
				gutterWidth:15								
			});		
		});	
		$('.infinite_scroll').masonry({ 
			itemSelector: '.masonry_brick',
			columnWidth:226,
			gutterWidth:15								
		});	
	}
	masonry();
	$('.item').fadeIn();
    /*$('.infinite_scroll').imagesLoaded(function(){
      $(this).masonry({ 
			itemSelector: '.masonry_brick',
			columnWidth:226,
			gutterWidth:15								
		});	
    });
	*/
    var sp = 1
	//console.log(typeof $(".infinite_scroll").infinitescroll);
    $(".infinite_scroll").infinitescroll({
        navSelector  	: "#more",
        nextSelector 	: "#more a",
        itemSelector 	: ".item",
        //bufferPx: -200,
        loading: {
            img: def.root+"statics/images/masonry_loading.gif",
            msgText: "加载更多商品",
            finishedMsg: '',
            finished: function(){
                sp++;
				//console.log(sp);
                if(sp>=def.waterfall_sp){
                    $("#more").remove();
                    $("#infscr-loading").hide();
                    $("#page").show();
                    $(window).unbind('.infscr');
                }
            }
        }
    }, function(newElements){
        var $newElems = $(newElements);
        $('.infinite_scroll').masonry('appended', $newElems, false);
        $newElems.fadeIn();
		item_callback();
		return;
        $newElems.find('.img img').lazyload({
            threshold:300,
            effect:"fadeIn",
            placeholder:def.root+"statics/images/grey.gif"
        }); 
    });		   
});

$(function(){ 
	uc_share(".top_share");
	$('.url_cookie').click(function(){ 
		$.cookie('redirect',window.location.href,{path:'/'});
	});
	$('.login_list a').click(function(){ 
		$.cookie('redirect',window.location.href,{path:'/'});	
	});	
});
/*
分享宝贝
*/
function uc_share(mixed){
	var context=$(mixed);
	function _callback(){ 
		$('.close',context).click(function(){ 
			$('.dialog',context).hide();											 
		});
		$('.submit',context).click(function(){ 
			var submit=$(this);
			
			submit.addClass('on').attr('disabled','disabled');
			$('.hint',context).html('宝贝信息抓取中……').show();
			var url=$.trim($('.url',context).val());
			if(url.length==0){ 
				$('.hint',context).html("<span class='error'>请输入网址!</span>");
				submit.removeClass('on').attr('disabled','');
				return;
			}
			$.post(def.root+'index.php?m=uc&a=items_collect',{url:url},function(data){ 
				data=data.data;
				submit.removeClass('on').attr('disabled','');
				if(data.err=='yet_exist'){ 
					$('.hint',context).html("<span class='error'>商品已经存在!</span>[<a href='"+data.url+"' target='_blank'>点击查看</a>]")
					return;
				}
				if(data.err=='remote_not_exist'){ 
					$('.hint',context).html("<span class='error'>抓取失败，网址错误!</span>")
					return;
				}			
				$('.hint',context).hide();
				$('.dialog',context).hide();

				data.uid=def.uid;
				
				var share_result_dialog=art.dialog({
					id:'share_result_dialog',
					title:'嗯~ 就是它吧',
					content:$('.result_dialog_wrap',context).html(),
					lock:true
				});			
				
				$('#share_result_dialog .title').html(data.title);
				$('#share_result_dialog .tags').val(data.tags);
				$('#share_result_dialog .img').html("<img src='"+data.simg+"'/>");
				
				var dialog=$('#share_result_dialog');
				
				$('.commit',dialog).click(function(){ 
					var cid=parseInt($("#share_result_dialog #cid").val());
					if(cid==0){ 
						alert('请选择分类!');
						return;
					}
					
					$(this).attr('disabled','disabled');
					data.cid=$("select[name='cid']",dialog).val();
					data.tags=$(".tags",dialog).val();
					data.remark=$(".remark",dialog).val();
					
					$.post(def.root+'index.php?m=uc&a=add_items',data,function(data){
						data=data.data;
						if(data=='success'){
							share_result_dialog.close();
							window.location.href=def.root+"index.php?m=uc&a=share_list";
						}
						$(this).attr('disabled','');
					},'json');							  
				});			
			},'json');											   
		});		
	}	
	$('.button,.uc_share_btn',context).click(function(){	
		var html="<div class='append'>"+$('#share_wrap').html()+"</div>";
		$(".append",context).remove();
		context.append(html);
		_callback();
		if($('.dialog:visible',context).size()>0){ 
			$('.dialog',context).hide();
		}else{ 
			$('.dialog',context).show();	
		}
	});
}
function login(){ 
	if(parseInt(def.uid)>0)return true;
	art.dialog({ 
		id:'login',
		title:'登录',
		content:$('#login_dialog_wrap').html(),
		lock:true
	});
	var context=$('#login_dialog');
	$('.login_list a').click(function(){ 
		$.cookie('redirect',window.location.href,{path:'/'});								  
	});
	$('.submit',context).click(function(){ 
		var name=$.trim($('#name',context).val());
		var passwd=$.trim($('#passwd',context).val());
		
		$.post(def.root+'index.php?m=uc&a=login',{name:name,passwd:passwd},function(data){ 
			data=data.data;
			if(data.err=="0"){ 
				$('.hint',context).html(data.msg);
				return;
			}
			window.location.href="";
		},'json');
	});
	return false;
}

//创建提示
function tips(context,msg,err){ 
	var html="<div class='append'>\
	<div class='tips'><div class='tips_content'>"+msg+"</div></div>\
	</div>";
	$('.append',context).remove();
	context.append(html);
	$('.tips_content',context).addClass(err);
	if(def.module=='cate'||def.module=='search'){ 
		$('.tips_content a',context).attr('target','_blank');	
	}

	$('.tips',context).show();
	//return;
	setTimeout(function(){ 
		$('.tips',context).fadeOut();
		$('.append',context).remove();
	},2000);
}
//添加评论
$(function(){ 
	var default_comment="对心爱的宝贝说几句话吧~！";
	$('#items_comments_info').focus(function(){ 
		if($.trim($(this).val())==default_comment){ 
			$(this).val("");												   
		}
	}).blur(function(){ 
		if($.trim($(this).val()).length==0){ 
			$(this).val(default_comment);
		}
	}).val(default_comment);
	
	$('#items_comments .btn').click(function(){ 
		if(!login())return;
		var info=$.trim($('#items_comments_info').val());
		if(info.length==0 || info==default_comment){ 
			alert("评论不能为空!");
			return;
		}
		$.post(def.root+"index.php?m=uc&a=add_comment",{items_id:items_id,uid:def.uid,info:info},function(data){ 																	
			page(def.root+"index.php?m=item&a=index&id="+items_id+"&p=1");
			cbpage();
			$('#items_comments_info').val(default_comment);
		},'json');													 
	});
	//分页
	function page(url){ 
		var pager="";
		if($('#items_comments .list li').size()!=0){
			pager=$('#items_comments #page_wrap').html();
		}else{ 
			//第一次添加评论
			$('#items_comments .list').height(32);
		}
		var height=$('#items_comments .list').height();
		var width=$('#items_comments .list').width();
		$('#items_comments .list').append("<div class='loading'></div>");
		$('#items_comments .loading').css({
			"height":height+"px",
			"width":width+"px"
		});
		$.post(url,function(data){ 
			data=data.data;		
			$('#items_comments .list_wrap').html(data.list);
			$('#comments_count').html(data.count);
			cbpage();
		},'json');	
	}
	
	function cbpage(){ 
		$('#items_comments .page_num a').click(function(){
			$(this).click(function(){return false;});
			//$(this).not('.prev,.next').addClass('current');
			page($(this).attr('href'));
			return false;
		});		
	}
	cbpage();
});

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
//将Ansi编码的字符串进行Base64编码
function base64_encode(input) {
  var output = "";
  var chr1, chr2, chr3 = "";
  var enc1, enc2, enc3, enc4 = "";
  var i = 0;

  do {
	chr1 = input.charCodeAt(i++);
	chr2 = input.charCodeAt(i++);
	chr3 = input.charCodeAt(i++);

	enc1 = chr1 >> 2;
	enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	enc4 = chr3 & 63;

	 if (isNaN(chr2)) {
		enc3 = enc4 = 64;
	 } else if (isNaN(chr3)) {
		enc4 = 64;
	 }

	 output = output + 
		keyStr.charAt(enc1) + 
		keyStr.charAt(enc2) + 
		keyStr.charAt(enc3) + 
		keyStr.charAt(enc4);
	 chr1 = chr2 = chr3 = "";
	 enc1 = enc2 = enc3 = enc4 = "";
  } while (i < input.length);

  return output;
}

//将Base64编码字符串转换成Ansi编码的字符串
function base64_decode(input) {
	var output = "";
	var chr1, chr2, chr3 = "";
	var enc1, enc2, enc3, enc4 = "";
	var i = 0;
	//if(typeof input.length=='undefined')return '';
	if(input.length%4!=0){
		return "";
	}
	var base64test = /[^A-Za-z0-9\+\/\=]/g;
	
	if(base64test.exec(input)){
		return "";
	}
	
	do {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));
		
		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;
		
		output = output + String.fromCharCode(chr1);
		
		if (enc3 != 64) {
			output+=String.fromCharCode(chr2);
		}
		if (enc4 != 64) {
			output+=String.fromCharCode(chr3);
		}
		
		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";
	
	} while (i < input.length);
	return output;
}
